<template>
  <div class="container" ref="mainCon">
    <topTitle :titleText="`巡查模板`"></topTitle>
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-form-item label="模板名称" class="row-padding-bottom">
            <el-input
              placeholder="请输入项目名称"
              clearable
              v-model="filterField.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="commonBut saveBtn funComBut searchBtn"
            >
              搜索
            </el-button>
            <el-button
              type="primary"
              icon="icon iconfont icontianjia"
              @click="addTemp"
              class="commonBut saveBtn funComBut"
            >
              创建模板
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          @selection-change="handleSelectionChange"
          tooltip-effect="dark"
          :data="tableList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          v-loading="loading"
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            prop="name"
            label="模板名称"
            :formatter="formatTd"
            width="240"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.name"
                :columnName="'name'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="nickName"
            label="创建人"
            align="center"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column label="操作" align="left" fixed="right" width="160">
            <template slot-scope="scope">
              <el-link type="primary" @click="handleAlert(scope.row, 'detail')"
                >模板详情</el-link
              >
              <el-link
                type="primary"
                v-sdc
                @click="handleAlert(scope.row, 'handle')"
                >编辑</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageSize="getpageSize"
          @getpageNo="getpageNo"
        ></Pagination>
      </div>
    </div>
    <!-- 创建模板 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showAdd"
      @close="closeDialog('eliminateBox')"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      class="addDia"
      width="640px"
    >
      <el-form
        :model="eliForm"
        inline
        :rules="ruleEliminate"
        ref="eliminateBox"
        label-width="92px"
      >
        <el-form-item label="模板名称：" prop="name" style="padding-top: 8px">
          <el-input
            type="text"
            placeholder="请输入模板名称"
            class="mWidth"
            clearable
            v-model="eliForm.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="巡查事项：" prop="ipqcItemList">
          <div class="itemsBox">
            <p>
              巡查事项的填写，文字描述尽量简洁简单为主，便于网格员巡查过程中落实（示例：是否现场有维权公示牌公示）
            </p>
            <div
              v-for="(item, index) in ipqcItemList"
              :key="index"
              class="elinputs"
            >
              <el-input
                type="text"
                placeholder="请输入巡查事项内容"
                class="mWidth"
                clearable
                v-model="item.name"
              ></el-input>
              <el-link
                style="margin-left: 8px"
                v-if="dialogTitle == '创建巡查模板' && ipqcItemList.length > 1"
                @click="delItems(index)"
                type="primary"
                >删除</el-link
              >
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label=" "
          style="margin-bottom: 0"
          v-if="dialogTitle == '创建巡查模板'"
        >
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icontianjia"
            plain
            @click="addItems"
          >
            <span class="opetareText">新增</span>
          </el-button>
        </el-form-item>
      </el-form>
      <div div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog('eliminateBox')" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="saveEli"
          v-sdc
          :loading="isSaveLoading"
          class="save"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 模板详情 -->
    <el-dialog
      title="查看巡查模板"
      :visible.sync="showLook"
      @close="closeDetialDialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      class="addDia"
      width="640px"
    >
      <div class="detailTitle mrT8">
        <span class="label">模板名称：</span>
        <span class="text">{{ detailInfo.name }}</span>
      </div>
      <div class="detailContent">
        <span class="label">巡查事项：</span>
        <div class="info">
          <div v-for="(item, index) in detailInfo.pcIpqcItemVOS" :key="index">
            {{ index + 1 }} . {{ item.name }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import scrollTable from '@/mixin/scrollTable.js'
export default {
  name: 'patrolTemp',
  mixins: [scrollTable],
  data() {
    var checkArea = (rule, value, callback) => {
      let lastArr = this.ipqcItemList
      let flag = true
      for (let i = 0; i < lastArr.length; i++) {
        if (!lastArr[i].name) {
          flag = false
          return callback(new Error('巡查事项内容不能为空'))
        } else {
          if (lastArr[i].name.length > 100) {
            flag = false
            return callback(new Error('巡查事项内容最多输入100个字符'))
          }
        }
      }
      if (flag) {
        callback()
      }
    }
    return {
      dialogTitle: '创建巡查模板',
      filterField: {
        name: '',
      },
      requestUrl: 'api-gov/pcipqc/template/list',
      tableList: [],
      loading: false,
      showAdd: false,
      eliForm: {
        name: '',
        ipqcItemList: [],
      },
      ipqcItemList: [
        {
          id: null,
          templateId: null,
          name: null,
          isDeleted: 1,
          createTime: null,
          updaterId: null,
          creatorId: null,
          updateTime: null,
          effectiveEndDate: null,
          effectiveStartDate: null,
        },
      ],
      ruleEliminate: {
        name: [
          { required: true, message: '请输入模板名称' },
          { required: true, max: 100, message: '最多输入100个字符' },
        ],
        ipqcItemList: [
          {
            required: true,
            validator: checkArea,
            trigger: ['blur', 'change'],
          },
        ],
      },
      isSaveLoading: false,

      showLook: false,
      detailInfo: {},
    }
  },
  mounted() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  methods: {
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    //新增
    addTemp() {
      this.eliForm.name = ''
      this.showAdd = true
      this.dialogTitle = '创建巡查模板'
    },
    //添加巡查内容
    addItems() {
      let lastArr = this.ipqcItemList
      let flag = true
      for (let i = 0; i < lastArr.length; i++) {
        if (!lastArr[i].name) {
          flag = false
        } else {
          if (lastArr[i].name.length > 100) {
            flag = false
          }
        }
      }
      if (!flag) {
        this.$refs.eliminateBox.validateField('ipqcItemList')
      } else {
        this.ipqcItemList.push({
          id: null,
          templateId: null,
          name: null,
          isDeleted: 1,
          createTime: null,
          updaterId: null,
          creatorId: null,
          updateTime: null,
          effectiveEndDate: null,
          effectiveStartDate: null,
        })
      }
    },
    //删除巡查内容
    delItems(index) {
      this.ipqcItemList.splice(index, 1)
      this.$refs.eliminateBox.validateField('ipqcItemList')
    },
    closeDialog() {
      this.showAdd = false
      this.dialogTitle = '创建巡查模板'
      this.ipqcItemList = [
        {
          id: null,
          templateId: null,
          name: null,
          isDeleted: 1,
          createTime: null,
          updaterId: null,
          creatorId: null,
          updateTime: null,
          effectiveEndDate: null,
          effectiveStartDate: null,
        },
      ]
      this.eliForm.name = ''
      this.$refs.eliminateBox.resetFields()
    },
    saveEli() {
      this.$refs.eliminateBox.validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          if (this.dialogTitle == '创建巡查模板') {
            this.axios
              .post('api-gov/pcipqc/template/add', {
                name: this.eliForm.name,
                ipqcItemList: JSON.stringify(this.ipqcItemList),
              })
              .then((res) => {
                this.isSaveLoading = false
                if (!res.data.hasError) {
                  this.$message({
                    message: '保存成功',
                    type: 'success',
                  })
                  this.searchList()
                  this.closeDialog()
                }
              })
          } else {
            let params = {
              id: this.detailInfo.id,
              name: this.eliForm.name,
              isDeleted: this.detailInfo.isDeleted,
              effectiveStartDate: this.detailInfo.effectiveStartDate,
              effectiveEndDate: this.detailInfo.effectiveEndDate,
              createTime: this.detailInfo.createTime,
              creatorId: this.detailInfo.creatorId,
              updateTime: this.detailInfo.detailInfo,
              updaterId: this.detailInfo.updaterId,
              ipqcItemList: JSON.stringify(this.ipqcItemList),
            }
            this.axios
              .post('api-gov/pcipqc/template/edit', params)
              .then((res) => {
                this.isSaveLoading = false
                if (!res.data.hasError) {
                  this.$message({
                    message: '保存成功',
                    type: 'success',
                  })
                  this.searchList()
                  this.closeDialog()
                }
              })
          }
        }
      })
    },
    handleAlert(item, str) {
      this.axios
        .post('api-gov/pcipqc/template/detail', { id: item.id })
        .then((res) => {
          if (!res.data.hasError) {
            this.detailInfo = res.data.result
            if (str == 'detail') {
              this.showLook = true
            } else {
              this.axios
                .post('api-gov/pcipqc/task/countTemplateTask', {
                  templateId: item.id,
                })
                .then((res) => {
                  if (!res.data.result) {
                    this.showAdd = true
                    this.dialogTitle = '编辑巡查模板'
                    this.eliForm.name = this.detailInfo.name
                    this.ipqcItemList = this.detailInfo.pcIpqcItemVOS
                  } else {
                    this.$message({
                      message: '该模板已创建巡查任务，无法修改。',
                      type: 'warning',
                    })
                  }
                })
            }
          }
        })
    },
    closeDetialDialog() {
      this.showLook = false
      this.detailInfo = {}
    },
  },
}
</script>
<style lang="less" scoped>
.addDia {
  .el-input {
    width: 394px;
  }
  .itemsBox {
    display: inline-block;
    p {
      width: 394px;
      color: #999;
      line-height: 18px;
      padding: 8px 0 10px;
    }
    .elinputs {
      margin-bottom: 16px;
      .el-link {
        height: 16px;
      }
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
.detailTitle {
  font-size: 14px;
  margin-bottom: 22px;
  color: #666;
  .label {
    // vertical-align: top;
    width: 115px;
    text-align: right;
    display: inline-block;
    color: #333;
    font-weight: 500;
  }
  .text {
    width: 420px;
    display: inline-block;
    // vertical-align: top;
  }
}
.detailContent {
  font-size: 14px;
  margin-bottom: 22px;
  color: #666;
  .label {
    width: 115px;
    text-align: right;
    display: inline-block;
    vertical-align: top;
    color: #333;
    font-weight: 500;
  }
  .info {
    width: 420px;
    display: inline-block;
    vertical-align: top;
  }
}
</style>
